<?php

namespace app\user\service;

use OSS\OssClient;
use OSS\Core\OssException;

class OssService {

  private $request;
  private $error = false;
  private $fileType;
  private $formName = 'file';

  public function __construct()
  {
      $this->request = request();
  }

  public function setFormName($name)
  {
    $this->formName = $name;
  }

  public function setFileType($fileType)
  {
      $this->fileType = $fileType;
  }

  public function upload () {
    $fileImage    = $this->request->file($this->formName);

    $originalName = $fileImage->getInfo('name');
    $strFileExtension = strtolower(cmf_get_file_extension($originalName));
    $strDate    = date('Ymd');

    $fileSaveName = date('Ymd') . '/' . md5(uniqid()) . "." . $strFileExtension;

    $accessKeyId = "LTAI2YDYx0NICU7t";
    $accessKeySecret = "2WXeqduvx5EXHcAoUQa6YrJnrFhkDD";
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    $endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // 存储空间名称
    $bucket= "youjushidai";
    $host = 'https://i.youjushidai.top';
    // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
    $filePath = $fileImage->getInfo('tmp_name');

    try{
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

        $res = $ossClient->uploadFile($bucket, $fileSaveName, $filePath);
        if (isset($res['info'])) {
          $info = $res['info'];
          $info['url'] = $host . '/' . $fileSaveName;
          $info['name'] = $originalName;
          return $info;
        }
    } catch(OssException $e) {
        return $e->getMessage();
    }
  }
}
